<?php

namespace app\api\controller\fishing;

use app\admin\model\FishingAcc;
use app\admin\model\FishingShare;
use app\common\controller\Api;
use think\Cache;
use think\Request;

/**
 * 天天去钓鱼其它操作接口
 */
class Options extends Api
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function __construct(Request $request = null)
    {
        header('Access-Control-Allow-Origin:*');
        parent::__construct($request);
    }

    // 根据查询条件获取所有任务信息
    public function get_taskitem_info($field)
    {
        $data['data'] = array();
        $data['user_id'] = array();
        $share = FishingShare::where($field)->column('item1, item2, item3, item4, item5, item6');
        foreach ($share as $key => $value) {
            foreach ($value as $v) {
                $item = explode(',', $v);
                array_push($data['user_id'], $item['0']);
                array_push($data['data'], $item['1']);
            }
        }
        return $data;
    }

    //判断任务最后更新时间是否是今天,进行操作
    public function checkTaskTime($field)
    {
        $share = FishingShare::where($field)->find();
        $updatetime = $share->updatetime;
        $begintoday= mktime(0,0,0,date('m'),date('d'),date('Y'));
        if ($updatetime < $begintoday) {
            $share->item1 = '0,0';
            $share->item2 = '0,0';
            $share->item3 = '0,0';
            $share->item4 = '0,0';
            $share->item5 = '0,0';
            $share->item6 = '0,0';
        }
        $share->save();
    }

    // 更新用户最后登出时间
    public function update_logout_time()
    {
        // 接受客户端信息
        $openid = $this->request->post('openid') ?: 'mnq';
        $acc = FishingAcc::get(['openid' => $openid]);
        $acc->last_logout_time = time(); // 获取服务器当前时间
        $acc->save();
        $this->success('ok');
    }

    // 获取任务数据
    public function get_task_info()
    {

        $openid = $this->request->post('openid');

        /**
         * 判断是否为模拟器
         * 判断是否第一次邀请
         */
        if ($openid && $openid != '' && $openid != 'undefined') {
            $acc = FishingAcc::get(['openid' => $openid]);
            if ($share = FishingShare::get(['fromUser' => $openid])) {
                $this->checkTaskTime(['fromUser' => $openid]);
                $result = $this->get_taskitem_info(['fromUser' => $openid]);
            } else {
                $s = new FishingShare;
                $s->fromUser = $openid;
                $s->item1 = '0,0';
                $s->item2 = '0,0';
                $s->item3 = '0,0';
                $s->item4 = '0,0';
                $s->item5 = '0,0';
                $s->item6 = '0,0';
                $s->save();
                $result = $this->get_taskitem_info(['fromUser' => $openid]);
            }
        } else {
            $acc = FishingAcc::get(1);
            $this->checkTaskTime(['id' => 1]);
            $result = $this->get_taskitem_info(['id' => 1]);
        }

        $money = $this->get_money_by_depth($acc->depth_level);

        $avatar = $this->handler_avatar($result['user_id']);
        $data = $result['data'];

        $result = [
            'code' => 0,
            'msg' => 'ok',
            'money' => $money,
            'avatar' => $avatar,
            'data' => $data,
        ];

        return json($result);
    }

    // 处理获取头像数据
    public function handler_avatar($list)
    {
        $return = array();
        foreach ($list as $id) {
            $acc = FishingAcc::get($id);
            if ($acc) {
                array_push($return, $acc->avatar_url ? $acc->avatar_url : 1);
            } else {
                array_push($return, '');
            }
        }
        return $return;
    }

    // 获取任务奖励接口
    public function get_task_money()
    {
        $openid = $this->request->post('openid') ?: 'mnq';
        $position = $this->request->post('position');

        $acc = FishingAcc::get(['openid' => $openid]);

        // 更新金钱
        $money = $this->get_money_by_depth($acc->depth_level);
        $acc->money += $money;

        $data['money'] = $acc->money;

        $result = $this->get_taskitem_info(['fromUser' => $openid]);
        $itemlist = $result['data'];

        // 判断机制
        foreach ($itemlist as $key => $item) {
            if ($key == $position) {
                if ($item) {
                    if ($item == 2) $this->error('重复领取奖励');
                    $itemlist[$key] = 2;
                } else {
                    $this->error('任务位置错误');
                }
            }
        }

        // 设置要更新的数据并更新
        if ($this->save_share_data($openid, $result['user_id'], $itemlist)) {
            $acc->save();
        }

        $this->result('ok', $data);
    }

    // 获取任务完成接口
    public function get_task_complete()
    {
        $fromUser = $this->request->post('fromUser'); // 来源用户
        $toUser = $this->request->post('toUser'); // 邀请用户
        $position = $this->request->post('position'); // 任务定位

        // 获取邀请用户id
        $acc = FishingAcc::get(['openid' => $toUser]);
        $toId = $acc->id;

        // 拿到来源用户的邀请数据
        $result = $this->get_taskitem_info(['fromUser' => $fromUser]);
        $id_list = $result['user_id'];
        $item_list = $result['data'];

        // 判断是否已经邀请过该用户
        foreach ($id_list as $id) {
            if ($id == $toId) $this->error('重复邀请用户');
        }

        // 判断是否邀请重复进入
        if (!$id_list[$position] && !$item_list[$position]) {
            $id_list[$position] = $toId;
            $item_list[$position] = 1;
        } else {
            $this->error('重复进入');
        }

        // 设置要更新的数据并更新
        if ($this->save_share_data($fromUser, $id_list, $item_list)) {
            $this->success('ok');
        } else {
            $this->error('error');
        }

    }

    // 保存邀请相关数据
    public function save_share_data($openid, $id_list, $item_list)
    {
        $task = array();
        for ($i = 0; $i < 6; $i++) {
            $item_data = $id_list[$i] . ',' . $item_list[$i];
            $item = ['item' . (intval($i) + 1) => $item_data];
            $task = array_merge($task, $item);
        }
        $share = FishingShare::get(['fromUser' => $openid]);
        return $share->save($task);
    }

    // 钓鱼结算接口
    public function get_fished_data()
    {
        $openid = $this->request->post('openid') ?: 'mnq';
        $money = $this->request->post('money');
        $collection = $this->request->post('collection');

        $acc = FishingAcc::get(['openid' => $openid]);

        $acc->money += $money;
        if ($acc->max_score < $money) {
            $acc->max_score = $money;
        }

        // 更新图鉴并返回新增的图鉴
        $collected = explode('_', $acc->collection);
        $collection = explode('_', $collection);

        $new = array_diff($collection, $collected);

        $newData = array();
        foreach ($new as $v) {
            array_push($newData, $v);
        }

        $newCollection = array_unique(array_merge($collection, $collected));
        $newCollectionStr = '';
        foreach ($newCollection as $k => $v) {
            if ($k != 0) $newCollectionStr = $newCollectionStr . '_';
            $newCollectionStr = $newCollectionStr . $v;
        }

        $acc->collection = $newCollectionStr;
        $acc->save();

        $data['money'] = $acc->money;
        $data['new'] = $newData;
        $data['max_score'] = $acc->max_score;

        $this->result('ok', $data);
    }

    // 设置收益倍数与获取条件
    public function set_multiple()
    {
        $rand = rand(2, 7);
        $data['multiple'] = $rand;
        $data['isVideo'] = false;
        $this->result('ok', $data);
    }

    // 获取图鉴接口
    public function get_collection()
    {
        $openid = $this->request->post('openid') ?: 'mnq';
        $collection = FishingAcc::where(['openid' => $openid])->value('collection');
        $this->result('ok', explode('_', $collection));
    }

    // 获取分享信息
    public function get_share_info()
    {
        $data = array(
            'type' => 1,
            'title' => '快来和我一起钓鱼吧!',
            'imgUrl' => 'https://xcx-1256535092.cos.ap-shanghai.myqcloud.com/fishing/share/09.jpg'
        );
        $this->result('ok', $data);
    }

    // 通过深度等级获取邀请好友得到金币数
    public function get_money_by_depth($level)
    {
        return 500 + floor($level / 8) * 500;
    }
}
